package com.yitao.cms.config.aopLog;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.skipper.base.json.JSON;
import com.skipper.base.json.JSONArray;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.operatorLog.OperatorLogDto;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.service.operatorLog.OperatorLogService;
import com.yitao.cms.service.user.cmsUser.OperationUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;


/**
 * @Auther: wuwenlong
 * @Date: 2018/8/3 0003 18:20
 * @Description:
 */
@Aspect
@Component
public class LogAopAction {
    private final Logger logger = LoggerFactory.getLogger(LogAopAction.class);
    @Autowired
    private OperatorLogService operatorLogService;
    @Autowired
    private OperationUserService userService;

    @Pointcut("@annotation(com.yitao.cms.config.aopLog.LogAnnotation) ")
    // @Pointcut("execution(public * com.yitao.cms.controller..*(..)) ")
    private void pointCutMethod() {
    }

    /**
     * 记录操作日志
     */
    @AfterReturning(value = "pointCutMethod()",returning = "rtv")  //执行后操作
    public void after(JoinPoint joinPoint, Object rtv) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession != null) {
            //获取请求参数
            String beanName = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();
            String url = request.getRequestURI();
            String remoteAddr = getIpAddr(request);
            String requestMethod = request.getMethod();
            try {
                String targetName = joinPoint.getTarget().getClass().getName();
                Class targetClass = Class.forName(targetName);
                Method[] methods = targetClass.getMethods();
                OperatorLogDto optLog = new OperatorLogDto();
                //请求参数
                if (request.getParameterMap()!=null && request.getParameterMap().isEmpty()!=true) {//dan
                    optLog.setRequestPara(JSON.toJSONString(request.getParameterMap()));
                }else {
                    Object[] object = joinPoint.getArgs();
                    if (object.length>1){
                        optLog.setRequestPara(JSON.toJSONString(object[1]));
                    }
                }
                optLog.setResponsePara(JSON.toJSONString(rtv));//返回参数
                for (Method method : methods) {
                    if (method.getName().equals(methodName)) {
                        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
                        if (logAnnotation != null) {
                            optLog.setDescription(logAnnotation.remark());
                            optLog.setTargetType(logAnnotation.targetType());

                        }
                    }
                }
                optLog.setOperatorUrl(url);
                optLog.setMethodName(methodName);
                optLog.setRemoteAddr(remoteAddr);
                operatorLogService.operatorLogAdd(optLog, request);
            } catch (Exception e) {
                logger.error("***操作请求日志记录失败doBefore()***", e);
            }
        }
    }

    /*@Around("pointCutMethod()")
    public Object doAround (ProceedingJoinPoint pjp) throws Throwable {
        OperatorLogDto optLog = new OperatorLogDto();

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        //补充参数
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession!=null){
            optLog.setOperatorName(userSession.getUserName());
            optLog.setCreateBy(String.valueOf(userSession.getId()));
            if (request.getParameterMap()!=null){//请求参数
                optLog.setRequestPara(JSON.toJSONString(request.getParameterMap()));
            }
            if (pjp.proceed()!=null){
                optLog.setResponsePara(JSON.toJSONString(pjp.proceed()));
            }
            Class<?> aClass = pjp.getTarget().getClass();
            String methodName = pjp.getSignature().getName();
            Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getParameterTypes(); //获取目标方法参数类型
            Method method = aClass.getMethod(methodName, parameterTypes);  //获取目标方法
            LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);  //获取方法上的注解
            optLog.setDescription(annotation.remark());
            optLog.setTargetType(annotation.targetType());
            optLog.setOperatorUrl(request.getRequestURI());
            optLog.setMethodName(request.getMethod());
            optLog.setRemoteAddr(getIpAddr(request));
            operatorLogService.operatorLogAdd(optLog, request);
        }
       return pjp.proceed();//proceed方法就是用于启动目标方法执行的
    }*/

   /* @AfterReturning(returning = "ret", pointcut = "pointCutMethod()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
    }*/

    /**
     * 获取登录用户远程主机ip地址
     *
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
